package com.ruoyi.web.controller.gd;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.gd.fj.domain.vo.ZFujianVo;
import com.ruoyi.gd.fj.service.IZFujianService;
import com.ruoyi.gd.wgd.domain.vo.ZWgdVo;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gd.ywd.domain.vo.ZYwdVo;
import com.ruoyi.gd.ywd.domain.bo.ZYwdBo;
import com.ruoyi.gd.ywd.service.IZYwdService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 业务单
 *
 * @author ruoyi
 * @date 2024-03-17
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/gd/ywd")
public class ZYwdController extends BaseController {

    private final IZYwdService iZYwdService;

    @Resource
    private final ISysDictTypeService dictTypeService;

    @Resource
    private IZFujianService fujianService;

    @Value("${upload.path}")
    private String uploadPath;

    /**
     * 通过首页跳转查询
     */
    @SaCheckPermission("gd:ywd:list")
    @GetMapping("/list/querySyList")
    public List<ZYwdVo> querySyList() {
        return iZYwdService.handleSyTz();
    }

    /**
     * 查询业务单列表
     */
    @SaCheckPermission("gd:ywd:list")
    @GetMapping("/list/calendar")
    public List<ZYwdVo> calendarList(ZYwdBo bo) {
        return iZYwdService.calendarList(bo);
    }

    /**
     * 查询业务单列表
     */
    @SaCheckPermission("gd:ywd:list")
    @GetMapping("/list/{type}")
    public TableDataInfo<ZYwdVo> list(ZYwdBo bo, PageQuery pageQuery, @PathVariable("type") String type, HttpServletRequest request) {
        return iZYwdService.queryPageList(bo, pageQuery, type);
    }

    /**
     * 导出业务单列表
     */
    @SaCheckPermission("gd:ywd:export")
    @Log(title = "业务单", businessType = BusinessType.EXPORT)
    @PostMapping("/export/{type}")
    public void export(ZYwdBo bo, HttpServletResponse response,@PathVariable("type") String type) {
        List<ZYwdVo> list = iZYwdService.queryList(bo, type);
        // 获取字典数据是否已下场
        List<SysDictData> sfyxcList = dictTypeService.selectDictDataByType("gd_xczt");
        // 获取字典数据是否回款
        List<SysDictData> sfhkList = dictTypeService.selectDictDataByType("gd_sfhk");
        // 处理数据
        for (int i = 0; i < list.size(); i++) {
            ZYwdVo zYwdVo = list.get(i);
            // 设置编号
            zYwdVo.setExcelId(i + 1 + "");
            // 设置是否已下场
            sfyxcList.forEach(item -> {
                if (item.getDictValue().equals(zYwdVo.getSfyxc())) {
                    zYwdVo.setSfyxc(item.getDictLabel());
                }
            });
            // 设置是否已回款
            sfhkList.forEach(item -> {
                if (item.getDictValue().equals(zYwdVo.getSfhk())) {
                    zYwdVo.setSfhk(item.getDictLabel());
                }
            });
        }
        ExcelUtil.exportExcel(list, "业务单", ZYwdVo.class, response);
    }

    /**
     * 导出选择数据
     */
    @Log(title = "业务单", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSelectDat/{ids}")
    public void exportSelectData(@PathVariable("ids") String ids, HttpServletResponse response) {
        List<ZYwdVo> list = iZYwdService.queryListByIds(ids);
        // 获取字典数据是否已下场
        List<SysDictData> sfyxcList = dictTypeService.selectDictDataByType("gd_xczt");
        // 获取字典数据是否回款
        List<SysDictData> sfhkList = dictTypeService.selectDictDataByType("gd_sfhk");
        // 处理数据
        for (int i = 0; i < list.size(); i++) {
            ZYwdVo zYwdVo = list.get(i);
            // 设置编号
            zYwdVo.setExcelId(i + 1 + "");
            // 设置是否已下场
            sfyxcList.forEach(item -> {
                if (item.getDictValue().equals(zYwdVo.getSfyxc())) {
                    zYwdVo.setSfyxc(item.getDictLabel());
                }
            });
            // 设置是否已回款
            sfhkList.forEach(item -> {
                if (item.getDictValue().equals(zYwdVo.getSfhk())) {
                    zYwdVo.setSfhk(item.getDictLabel());
                }
            });
        }
        ExcelUtil.exportExcel(list, "业务单", ZYwdVo.class, response);
    }


    /**
     * 获取业务单详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("gd:ywd:query")
    @GetMapping("/{id}")
    public R<ZYwdVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String id) {
        return R.ok(iZYwdService.queryById(id));
    }

    /**
     * 新增业务单
     */
    @SaCheckPermission("gd:ywd:add")
    @Log(title = "业务单", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ZYwdBo bo) {
        return toAjax(iZYwdService.insertByBo(bo));
    }

    /**
     * 修改业务单
     */
    @SaCheckPermission("gd:ywd:edit")
    @Log(title = "业务单", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ZYwdBo bo) {
        return toAjax(iZYwdService.updateByBo(bo));
    }

    /**
     * 删除业务单
     *
     * @param ids 主键串
     */
    @SaCheckPermission("gd:ywd:remove")
    @Log(title = "业务单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iZYwdService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 重新授权数据
     *
     * @param ids 主键串
     */
    @Log(title = "重新授权数据", businessType = BusinessType.DELETE)
    @GetMapping("/authData/{ids}")
    public R<Void> authData(@PathVariable String[] ids) {
        return toAjax(iZYwdService.authData(ids));
    }

    @GetMapping(value = "/downExcel", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void downExcel(@RequestParam("ids") String ids,  HttpServletResponse response) throws IOException {
        // 获取数据
        List<ZYwdVo> list = iZYwdService.selectByIds(ids.split(","));
        // 查询出来业务单，从业务单中获取所有的附件id
        List<String> collect = list.stream().map(item -> item.getFj()).collect(Collectors.toList());
        // 通过附件id，将附件查询出来
        List<ZFujianVo> fjList = fujianService.queryListByIds(collect);

        // 创建一个字节数组输出流，用于收集压缩后的数据
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(baos);
        try{
            for (int i = 0; i < fjList.size(); i++) {
                ZFujianVo zFujianVo = fjList.get(i);
                File file = new File(uploadPath + zFujianVo.getFjpath());
                if (file.exists()) {
                    FileInputStream fileInputStream = new FileInputStream(file);
                    byte[] data = new byte[fileInputStream.available()];
                    // 将数据读取到数组中
                    fileInputStream.read(data);
                    // 设置压缩包栏目
                    zip.putNextEntry(new ZipEntry((i+1) +  "_" +zFujianVo.getFjname()));
                    // 将数据写入压缩包中
                    zip.write(data);
                    zip.flush();
                    zip.closeEntry();
                    fileInputStream.close();
                }
            }
            IOUtils.closeQuietly(zip);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] zipData = baos.toByteArray();
        exportData(response, zipData);
    }

    /**
     * 生成zip文件
     */
    private void exportData(HttpServletResponse response, byte[] data) throws IOException
    {
        response.reset();
//        response.addHeader("Access-Control-Allow-Origin", frontpath);
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,X-App-Id, X-Token, Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"asp.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        response.setHeader("Access-Control-Allow-Credentials", "true");

        IOUtils.write(data, response.getOutputStream());
    }

    @GetMapping(value = "/downExcel/wgd", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void downExcelWgd(@RequestParam("ids") String ids,  HttpServletResponse response) throws IOException {
        // 获取数据
        List<ZYwdVo> list = iZYwdService.selectByIdsWgd(ids.split(","));
        List<ZWgdVo> wgdList = new ArrayList();
        list.forEach(item -> {
            if (item.getWgdList() != null && item.getWgdList().size() > 0) {
                wgdList.addAll(item.getWgdList());
            }
        });
        // 查询出来业务单，从业务单中获取所有的附件id
        List<String> collect = wgdList.stream().map(item -> item.getFj()).distinct().collect(Collectors.toList());
        // 通过附件id，将附件查询出来
        List<ZFujianVo> fjList = fujianService.queryListByIds(collect);

        // 创建一个字节数组输出流，用于收集压缩后的数据
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(baos);
        try{
            for (int i = 0; i < fjList.size(); i++) {
                ZFujianVo zFujianVo = fjList.get(i);
                File file = new File(uploadPath + zFujianVo.getFjpath());
                if (file.exists()) {
                    FileInputStream fileInputStream = new FileInputStream(file);
                    byte[] data = new byte[fileInputStream.available()];
                    // 将数据读取到数组中
                    fileInputStream.read(data);
                    // 设置压缩包栏目
                    zip.putNextEntry(new ZipEntry((i+1) +  "_" +zFujianVo.getFjname()));
                    // 将数据写入压缩包中
                    zip.write(data);
                    zip.flush();
                    zip.closeEntry();
                    fileInputStream.close();
                }
            }
            IOUtils.closeQuietly(zip);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] zipData = baos.toByteArray();
        exportData(response, zipData);
    }

}
